const configapiPath = '/api/config/'
const apiPath = '/api/navigation/'

const $homeIframe = $('#homeIframe')
const $configForm = $('#configForm')

async function getConfigForm() {
	try {
		const { code, msg, data } = await $.ajax({
			url: configapiPath + 'getHomeContentShowOrHidden',
			type: 'GET',
		})
		
		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		for (const [key, value] of Object.entries(data)) {
			const isOn = Number(value) > 0 ? 'On' : 'Off'
			$(`#${key}${isOn}`).prop('selected', true)
		}
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

$configForm.on('submit', function (e) {
	e.preventDefault()
	
	const formData = $(this).serializeArray()

	const formObject = formData.reduce((acc, { name, value }) => {
		acc[name] = acc[name] !== undefined 
			? [...[acc[name]].flat(), Number(value)] 
			: Number(value)
		return acc
	}, {})

	$.ajax({
		url: `${configapiPath}changeHomeContentShowOrHidden`,
		data: JSON.stringify(formObject),
		type: 'POST',
		dataType: 'json',
		async: false,
		contentType: 'application/json',
		success: function(res) {
			const { code, msg } = res
			if (code !== 200) {
				showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}
			showNotify(msg, 'success', 5000, 'mdi mdi-alert', 'top', 'right')
			getConfigForm()
			$homeIframe.attr('src', $homeIframe.attr('src'))
		},
		error: function(error) {
			console.error('服务器有误: ', error);
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		}
	})
})

async function get() {
	const $siteTable = $('#siteTable')
	$siteTable.text('加载中...')

	try {
		const response = await $.ajax({
			url: apiPath + 'get',
			type: 'GET',
		})
			
		const { code, msg, data } = response
		
		if (code !== 200) {
			$siteTable.text(msg)
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		let tr = ''

		data.forEach(item => {
			tr += `
				<tr class="text-center align-middle">
					<td>${item.id}</td>
					<td>
						${item.icon ? `<img class="lazyload" data-src="${item.icon}" style="height: auto; max-width: 30px;">` : '<p style="height: 100px; line-height: 100px;">跳转</p>'}
					</td>
					<td>${item.link ? `<a href="${item.link}" target="_blank" rel="noopener noreferrer">${item.link}</a>` : '不跳转'}</td>
					<td>
						${item.pic ? `<img class="lazyload" data-src="${item.pic}" style="max-height: 100px; min-width: 60px;">` : '<p style="height: 100px; line-height: 100px;">跳转</p>'}
					</td>
					<td>
						<div class="btn-group btn-group-sm">
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="编辑"
								onclick="set(${item.id}, '${item.icon}', '${item.link || ''}', '${item.pic || ''}')"
							><i class="mdi mdi-pencil"></i></a>
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="移除"
								onclick="del(${item.id})"
							><i class="mdi mdi-window-close"></i></a>
						</div>
					</td>
				</tr>
			`
		})
		$siteTable.html(tr)

		$('.lazyload').lazyload({
			root: null,
			rootMargin: '100px',
			threshold: 0
		})
		// 渲染工具
		renderTooltip()
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

async function add() {
	$.confirm({
		title: '新增导航',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">导航图标</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-icon" placeholder="请输入图标链接" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">导航链接</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" placeholder="请输入导航链接" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">弹出图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-pic" placeholder="请输入弹出图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const icon = that.find('#input-icon').val()
					const link = that.find('#input-link').val()
					const pic = that.find('#input-pic').val()

					const data = {
						icon,
						link: link || null,
						pic: pic || null
					}

					if (!data.icon) {
						$.alert({
							title: '',
							content: '图标链接不得为空',
							type: 'orange'
						})
						return false
					}

					if (!$.trim(link) && !$.trim(pic)) {
						$.alert({
							title: '',
							content: '跳转链接和淡出图片必须填写一个值',
							type: 'orange'
						})
						return false
					}

					if ($.trim(link) && $.trim(pic)) {
						$.alert({
							title: '',
							content: '跳转链接和淡出图片只能填写一个值',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: apiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '添加成功',
								type: 'green'
							})

							get()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

async function set(id, icon, link, pic) {
	$.confirm({
		title: '更新导航',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">导航图标</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-icon" value="${icon}" placeholder="请输入图标链接" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">导航链接</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" value="${link}" placeholder="请输入导航链接" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">弹出图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-pic" value="${pic}" placeholder="请输入弹出图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const icon = that.find('#input-icon').val()
					const link = that.find('#input-link').val()
					const pic = that.find('#input-pic').val()

					const data = {
						id,
						icon,
						link: link || null,
						pic: pic || null
					}

					if (!data.icon) {
						$.alert({
							title: '',
							content: '图标链接不得为空',
							type: 'orange'
						})
						return false
					}

					if (!$.trim(link) && !$.trim(pic)) {
						$.alert({
							title: '',
							content: '跳转链接和淡出图片必须填写一个值',
							type: 'orange'
						})
						return false
					}

					if ($.trim(link) && $.trim(pic)) {
						$.alert({
							title: '',
							content: '跳转链接和淡出图片只能填写一个值',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: apiPath + 'set',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '更新成功',
								type: 'green'
							})

							get()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

function del(id) {
	$.confirm({
		title: `确定删除id为: ${id}的站点吗`,
		content: '确定删除吗?',
		type: 'red',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-danger',
				action: function () {
					$.ajax({
						url: apiPath + `del?id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							get()
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}

$(document).ready(function (e) {
	$('input, textarea').attr('autocomplete', 'off')
	getConfigForm()
	get()
})